/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.controllers', [])
    .controller('MainCtrl',function($scope,$state,$window,MainService,AuthenticationService){
        $scope.islogin = AuthenticationService.isLogged;
        $('#slides2').slidesjs({
            width: 940,
            height: 528,
            navigation: false,
            start: 3,
            play: {
                auto: true
            }
        });

        $scope.myScroll = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        $scope.go = function(type){
            switch (type){
                case 1:
                    $state.go('tab.myTransfer',{random:false});
                    break;
                case 2:
                    $state.go('tab.bid');
                    break;
                case 3:
                    $state.go('tab.myOrders');
                    break;
                case 4:
                    $state.go('tab.center');
                    break;
                case 5://注销
                    $state.go('tab.line');
                    break;
                case 6:
                    $state.go('register');
                    break;
                case 7:
                    $state.go('login');
                    break;
                case 8:
                    $state.go('tab.mySuggest');
                    break;
            }


        }
    })
    .controller('TransferCtrl',function($scope,$state,$location,TransferService){
        //alert(TransferService.getInforData().startCityId+' '+TransferService.getInforData().startCity);
        //$scope.citys =[{name:'广州'},{name:'哈尔滨'},{name:'西安'},{name:'南京'},{name:'哈尔滨'},{name:'西安'},{name:'南京'}];

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.goNext = function(){
            $state.go('tab.transferAddCar');
        }
        $scope.inforData = {};
        if(!TransferService.getCityList().length>0){//如果初始化过城市则不再请求，直接赋值到页面
            TransferService.getCitys($scope);
        }else{
            $scope.inforData = TransferService.getInforData();
        }

        //$scope.inforData.phone = Number(JSON.parse(localStorage.getItem('user')).phone);
        $scope.selectCity = function(type){//1起点 2目的地
            //alert(type);
            TransferService.getInforData().username = $scope.inforData.username;
            TransferService.getInforData().phone = $scope.inforData.phone;
            /*TransferService.getInforData().startTime = $("#date1").val();
            TransferService.getInforData().endTime = $("#date2").val();*/
            $state.go('tab.citys',{type:type});
        }
        $("#dtBox").DateTimePicker({//各平台兼容性不同，创建了两个实例
            addEventHandlers: function()
            {
                var dtPickerObj = this;

                $("#pickerButton").click(function(e)
                {
                    e.stopPropagation();
                    dtPickerObj.showDateTimePicker($("#date1"));
                });

            }
        });
        $("#dtBox1").DateTimePicker({

            addEventHandlers: function()
            {
                var dtPickerObj = this;

                $("#pickerButton1").click(function(e)
                {
                    e.stopPropagation();
                    dtPickerObj.showDateTimePicker($("#date2"));
                    dtPickerObj._setCurrentDate();
                });
            }
        });

        $('#date1').bind('change',function(){//jquery监听隐藏文本框值变化
            TransferService.getInforData().startTime = this.value;
            $scope.inforData.startTime = this.value;
            $scope.$apply();
            $scope.myScroll.refresh();

        });
        $('#date2').bind('change',function(){
            TransferService.getInforData().endTime = this.value;
            $scope.inforData.endTime = this.value;
            $scope.$apply();
            $scope.myScroll.refresh();
        });


    })
    .controller('MyTransferCtrl',function($scope,$http,$state,MyTransferService){
        //$scope.datas=MyTransferService.getMytransferData().datas;
        $scope.pop1=false;
        $scope.cancelPop=function(){
            $scope.pop1=false;
        }
        $scope.go = function(go,trans,nums){
            if(go==1){
                var inforid=trans.id;
                setTimeout(function(){
                    var  promise = $http({
                        method:'POST',
                        url:'/bidTest',
                        data:{
                            inforid:inforid
                        }
                    });
                    promise.success(function(status) {
                        if(status){
                            $state.go('tab.outDetails',{startstation:trans.startstation,endstation:trans.endstation,starttime:trans.starttime,endtime:trans.endtime,type:trans.type,num:trans.num,carnum:trans.carnum,nums:nums,infoid:trans.id,picpath:trans.picpath,userid:trans.userid,phone:trans.phone});

                        }else{
                            $scope.pop1=true;
                        }
                    });
                    $scope.$apply();
                    if($scope.myScroll){
                        $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                    }
                },500);
            }else if(go==2){
                $state.go('tab.myTransfer2',{inforid:trans.id});
            }

        }
    })
    .controller('myTransfer2',function($scope,$state,$stateParams,TransferService){
      /*  $scope.myScroll = new IScroll('#wrapperTran', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
*/
        $scope.hid=false;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.goBack = function() {
            $state.go('tab.myTransfer');
        }
        $scope.goCompany=function(inforid,userid){
            $state.go('tab.companyDet',{inforid:inforid,userid:userid});
        }
    })
    .controller('OutDetails',function($scope,$state,$http,$stateParams,TransferService){

        var startstation=$stateParams.startstation;
        var endstation=$stateParams.endstation;
        var starttime=$stateParams.starttime;
        var endtime=$stateParams.endtime;
        var type=$stateParams.type;
        var num=$stateParams.num.split(',');
        var carnums=$stateParams.carnum;
        var nums=$stateParams.nums;
        var infoid=$stateParams.infoid;
        var picpath=$stateParams.picpath;
        var userid=$stateParams.userid;
        var phone=$stateParams.phone;
        var  promise = $http({
            method:'POST',
            url:'/outDetails',
            data:{
                carnum:carnums
            }
        });
        promise.success(function(data,status) {
            var brand=carnums.split(',');
            var pic=picpath.split(',');
            $scope.startstation = startstation;
            $scope.endstation=endstation;
            $scope.starttime=starttime;
            $scope.endtime=endtime;
            $scope.carnum=num; //辆数
            $scope.type=type; //类型(板车or拼装)
            $scope.infoid=infoid; //发车单id
            $scope.userid=userid;
            var docs=[]; //品牌id，品牌，型号
            for(var i=0;i<brand.length;i++){
                for(var j=0;j<data.result.length;j++){
                    if(brand[i]==data.result[j].id.toString()){
                        var doc={};
                        doc.bid=data.result[j].id.toString(); //品牌id
                        doc.num=data.result[j].num;  // 型号
                        doc.pic=pic[i];
                        doc.carbrand=data.result[j].carbrand; //品牌
                        docs.push(doc);
                    }else{
                    }
                }
            }
            $scope.result = docs;
            //一口竞价
            $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
            document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
            //$scope.bidding =function(infoid){
            //    $state.go('tab.bidding',{startstation:startstation,endstation:endstation,starttime:starttime,endtime:endtime,type:type,num:$stateParams.num,carnum:carnums,nums:nums,infoid:infoid,picpath:picpath,userid:userid});
            //}

        });
        $('#bidding').click(function(){
             setTimeout(function(){//因为有冲突等会执行scope.$apply();
                 var promise = $http({
                     method:'POST',
                     url:'/bidding',
                     data:{
                     }
                 });
                 promise.success(function(datas) {
                     if(datas[0].company){
                         if(datas[0].carrierauthstate==0){
                             console.log(datas[0]);
                             $scope.Pop1 = true;
                             $scope.content="您还没有认证，是否认证？"
                         }else{
                             $state.go('tab.bidding', {
                                 startstation: startstation,
                                 endstation: endstation,
                                 starttime: starttime,
                                 endtime: endtime,
                                 type: type,
                                 num: $stateParams.num,
                                 carnum: carnums,
                                 nums: nums,
                                 infoid: infoid,
                                 picpath: picpath,
                                 userid: userid,
                                 phone:phone
                             });
                         }
                     }else{
                         $scope.Pop = true;
                         $scope.content="请完善公司名称或个人姓名再竞价。"
                     }

                 });
                 $scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $scope.goBack = function(){
            $state.go('tab.myTransfer');
        }
        $scope.pop1=false;
        $scope.Pop=false;
        $scope.Pop1=false;
        $scope.bigImg = function(userid,pic) {
            $scope.pop1 = true;
            $scope.picpath = "../image/userimg/"+userid+"/"+pic;

        }
        $('#next').click(function(e){
            $scope.Pop=false;
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });

        $('.goCenter').click(function(e){
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $state.go('tab.center');
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $('.goCenter1').click(function(e){
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $state.go('tab.myAuth');
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $('.cancelPop').click(function(e){
            $scope.pop1=false;
            $scope.Pop1=false;
            setTimeout(function(){//因为有冲突等会执行scope.$apply();

                $scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        })
        $('.cancelPop1').click(function(e){
            $scope.Pop1=false;

            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $state.go('tab.bidding', {
                    startstation: startstation,
                    endstation: endstation,
                    starttime: starttime,
                    endtime: endtime,
                    type: type,
                    num: $stateParams.num,
                    carnum: carnums,
                    nums: nums,
                    infoid: infoid,
                    picpath: picpath,
                    userid: userid,
                    phone:phone
                });

                $scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        })
    })
    .controller('bidding',function($scope,$rootScope,$state,$http,LoginService,$stateParams,TransferService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, true);
        var startstation=$stateParams.startstation;
        var endstation=$stateParams.endstation;
        var starttime=$stateParams.starttime;
        var endtime=$stateParams.endtime;
        var type=$stateParams.type;
        var num=$stateParams.num;
        var carnums=$stateParams.carnum;
        var nums=$stateParams.nums;
        var phone=$stateParams.phone;
        var inforid=$stateParams.infoid;
        var picpath=$stateParams.picpath;
        var startTime=formatDate((new Date()),"yyyy-MM-dd");
        $scope.inforData = {startTime:startTime,endTime:startTime};
        //$scope.inforData = TransferService.getInforData();
        function formatDate(date,format){
            var paddNum = function(num){
                num += "";
                return num.replace(/^(\d)$/,"0$1");
            }
            //指定格式字符
            var cfg = {
                yyyy : date.getFullYear() //年 : 4位
                ,yy : date.getFullYear().toString().substring(2)//年 : 2位
                ,M  : date.getMonth() + 1  //月 : 如果1位的时候不补0
                ,MM : paddNum(date.getMonth() + 1) //月 : 如果1位的时候补0
                ,d  : date.getDate()   //日 : 如果1位的时候不补0
                ,dd : paddNum(date.getDate())//日 : 如果1位的时候补0
                ,hh : date.getHours()  //时
                ,mm : date.getMinutes() //分
                ,ss : date.getSeconds() //秒
            }
            format || (format = "yyyy-MM-dd hh:mm:ss");
            return format.replace(/([a-z])(\1)*/ig,function(m){return cfg[m];});
        }
        $("#dtBox").DateTimePicker({//各平台兼容性不同，创建了两个实例
            addEventHandlers: function()
            {
                var dtPickerObj = this;

                $("#pickerButton").click(function(e)
                {
                    e.stopPropagation();
                    dtPickerObj.showDateTimePicker($("#date1"));
                });

            }
        });
        $("#dtBox1").DateTimePicker({

            addEventHandlers: function()
            {
                var dtPickerObj = this;

                $("#pickerButton1").click(function(e)
                {
                    e.stopPropagation();
                    dtPickerObj.showDateTimePicker($("#date2"));
                    dtPickerObj._setCurrentDate();
                });
            }
        });

        $('#date1').bind('change',function(){//jquery监听隐藏文本框值变化
            TransferService.getInforData().startTime = this.value;
            $scope.inforData.startTime = this.value;
            $scope.$apply();
            $scope.myScroll.refresh();

        });
        $('#date2').bind('change',function(){
            TransferService.getInforData().endTime = this.value;
            $scope.inforData.endTime = this.value;
            $scope.$apply();
            $scope.myScroll.refresh();
        });
        var  promise = $http({
            method:'POST',
            url:'/bidding',
            data:{
                inforid:inforid
            }
        });
        promise.success(function(data) {
            $scope.company=data[0].company;  //公司名称
            $scope.carrierauthstate=data[0].carrierauthstate; //是否认证
            $scope.headerpath=data[0].headerpath;
            $scope.myphone=data[0].phone;
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.$apply(element);
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $scope.goBack = function(){
            $state.go('tab.outDetails',{startstation:startstation,endstation:endstation,starttime:starttime,endtime:endtime,type:type,num:$stateParams.num,carnum:carnums,nums:nums,infoid:inforid,phone:phone,picpath:picpath});
        }
        $scope.pop1=false;

        $scope.subBid = function(data){
            console.log(new Date(data.startTime).getTime());
            function daysBetween(DateOne,DateTwo)
            {
                var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));
                var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);
                var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));

                //var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('/'));
                //var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('/')+1);
                //var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('/'));
                var date = new Date();
                var month = date.getMonth()+1;
                var day = date.getDate();
                if(month<10){
                    month = '/0'+month;
                }else{
                    month = '/'+month
                }
                if(day<10){
                    day = '/0'+day;
                }else{
                    day = '/'+day;
                }
                var dd = date.getFullYear()+month+day;
                var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(dd))/86400000);
                return cha;
            }
            var isstartDate=daysBetween(data.startTime);
            var isendDate=daysBetween(data.endTime);
            if(data.price){
                if(isstartDate<0||isendDate<0){
                    $scope.pop1=true;
                    $scope.content="启程或到货日期不能小于当前日期。";
                    $scope.typebtn=2;
                    if($scope.myScroll){
                        $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                    }
                }else{
                    if(data.price.replace(/^[0-9]*$/,'1')==1&&new Date(data.endTime).getTime()>=new Date(data.startTime).getTime()){

                        $scope.pop1=true;
                        $scope.content="确定竞价吗？";
                        $scope.typebtn=1;
                        if($scope.myScroll){
                            $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                        }
                    }else{
                        if(new Date(data.endTime).getTime()<new Date(data.startTime).getTime()){
                            $scope.pop1=true;
                            $scope.content="到货日期不能小于启运日期。";
                            $scope.typebtn=2;
                            if($scope.myScroll){
                                $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        }else{
                            $scope.pop1=true;
                            $scope.content="请输入正确数字。";
                            $scope.typebtn=2;
                            if($scope.myScroll){
                                $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        }
                    }
                }
            }else{

                $scope.pop1=true;
                $scope.content="价格不能为空。";
                $scope.typebtn=2;
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }

            }
        }
        $scope.cancelPop = function(){
            $scope.pop1=false;
        }
        $scope.confirm = function(typebtn,inforData,myphone,company){
            if(typebtn==2){
                $scope.pop1=false;
            }else{
                var promise = $http({
                    method:'POST',
                    url:'/bidPost',
                    data:{
                        inforData:inforData,
                        inforid:inforid
                    }
                });
                promise.success(function(data) {
                    if(data){
                        if(company){
                            LoginService.bid(phone,company,myphone,inforData.price)
                                .success(function(data,status){
                                }
                            );
                        }else{
                            LoginService.bid(phone,false,myphone,inforData.price)
                                .success(function(data,status){
                                }
                            );
                        }
                        $rootScope.refreshBid = true;
                        $state.go('tab.jump',{isOk:true});
                        setTimeout(function(){//因为有冲突等会执行scope.$apply();
                            $scope.$apply(element);
                            if($scope.myScroll){
                                $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        },500);
                    }else{
                        $scope.pop1=true;
                        $scope.content="您已竞价过此订单，不可再竞价。";

                        setTimeout(function(){//因为有冲突等会执行scope.$apply();
                            $scope.typebtn=2;
                            if($scope.myScroll){
                                $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        },500);

                    }
                });
            }
        }
    })
    .controller('Jump',function($scope,$state,$stateParams,$interval){
        $scope.isOk = $stateParams.isOk;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.times=3;
        var timer = $interval(function(){
            $scope.times-=1;
            if($scope.times==0){
                $scope.times= 0;
                $interval.cancel(timer);
                $state.go('tab.bid');
            }
        },1000);

        $scope.goBid=function(){
            $state.go('tab.bid');
        }
        $scope.goBack = function(){
            $state.go('tab.myTransfer',{random:false});
        };

    })
    .controller('line',function($scope,$state,$http,MyTransferService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        /*$scope.goMain = function(){
            $state.go('main');
        }*/
        var arrs;
        var promise = $http({
            method:'POST',
            url:'/getLine',
            data:{
            }
        });
        promise.success(function(data) {
            $scope.datas=data;
            arrs=data;
        })

        $scope.pop1=false;
        $scope.deleteLine=function(index,doc){
            $scope.pop1=true;
            $scope.content="确定要删除此条专线吗？"
            $scope.data=doc;
            $scope.index=index;
        }
        $scope.cancelPop = function(){  //取消
            $scope.pop1=false;
        }
        $scope.confirm = function(index,doc){
            var promise = $http({
                method:'POST',
                url:'/deleteLine',
                data:{
                    id:doc.id
                }
            });
            promise.success(function(data) {
                setTimeout(function(){//因为有冲突等会执行scope.$apply();
                    $scope.pop1=false;
                    arrs.splice(index,1);
                    $scope.$apply();
                    if($scope.myScroll){
                        $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                    }
                },500);

            })
        }
        $scope.addLine = function(){
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $state.go('tab.addLine');
                $scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);

        }
    })
    .controller('addLine',function($scope,$state,$http,$location,TransferService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.goBack = function(){
            $state.go('tab.line');
        }
        $scope.subLine = function(inforData){  //点击添加
            if(inforData.price){
                if(inforData.price.replace(/^[0-9]*$/,'1')==1){
                    $scope.pop1=true;
                    $scope.content="确定添加专线吗？";
                    $scope.typebtn=1;
                }else{
                    $scope.pop1=true;
                    $scope.content="请输入正确的价格(价格为正整数)。";
                    $scope.typebtn=2;
                }
            }else{
                $scope.pop1=true;
                $scope.content="价格不能为空。";
                $scope.typebtn=2;
            }
        }
        $scope.cancelPop = function(){  //取消
            $scope.pop1=false;
        }
        $scope.confirm = function(typebtn,inforData){  //确定
            if(typebtn==1){
                $scope.pop1=false;
                var infordata={};
                infordata.startstation=inforData.startCity;
                infordata.endstation=inforData.endCity;
                infordata.price=inforData.price;
                var promise = $http({
                    method:'POST',
                    url:'/subLine',
                    data:{
                        inforData:infordata
                    }
                });
                promise.success(function(result) {
                    if(result){
                        setTimeout(function(){
                            $state.go('tab.line');
                            $scope.$apply();
                        },500);
                    }else{
                        $scope.pop1=true;
                        $scope.content="已有此专线。";
                        $scope.typebtn=2;
                    }
                })

            }else{
                $scope.pop1=false;
            }
        }
        $scope.inforData = {};
        if(!TransferService.getCityList().length>0){//如果初始化过城市则不再请求，直接赋值到页面
            TransferService.getCitys($scope);
        }else{
            $scope.inforData = TransferService.getInforData();
        }
        $scope.pop1=false;
        $('#pop1button').click(function(e)
        {
            $scope.pop1=false;
            setTimeout(function(){
                $scope.$apply();
            },500);
        });
        $scope.selectCity = function(type){//1起点 2目的地
            $state.go('tab.addCitys',{type:type});
        }
    })
    .controller('AddCitys',function($scope,$state,$stateParams,TransferService){
        $scope.citys = TransferService.getCityList();
        $scope.allcitys = TransferService.getAllCitys();
        $scope.provinces = TransferService.getProvince();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        $scope.myScroll1 = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll

        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
            $scope.myScroll1.refresh();
        },500);
        $scope.goBack = function(){
            $state.go('tab.addLine');
        };
        $scope.selectCity = function(id,province,city){//判断上一页面传来的值是1则改变事发地点2为目的地
            if($stateParams.type==1){
                TransferService.getInforData().startCityId = id;
                TransferService.getInforData().startCity = province+" "+city;

            }else if($stateParams.type==2){
                TransferService.getInforData().endCityId = id;
                TransferService.getInforData().endCity = province+" "+city;
            }
            $state.go('tab.addLine');
        };


        $scope.selectProvince = function(province){/*选择省份*/
            var citys = [];
            for(var i=0;i<$scope.allcitys.length;i++){
                if(province==$scope.allcitys[i].province){
                    citys.push($scope.allcitys[i]);
                }
            }
            $scope.citys = citys;
            //this.style.backgroundColor=this.style.backgroundColor==''?'#a00':'';return false;
            /*$(this).css('color','#a00');*/
            setTimeout(function(){
                $scope.$apply();
                $scope.myScroll1.refresh();

            },500);
        }

    })
    .controller('LoginCtrl',function($scope,$state,$window,$timeout,LoginService,AuthenticationService){
        $scope.pop01 = false;
        $scope.content="请完善公司名称或个人姓名。";
        $scope.login = function(){
            LoginService.login($scope.user.phone,$scope.user.password)
                .success(function(data,status){

                    AuthenticationService.isLogged = true;//认证成功

                    localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    localStorage.setItem('token',data.token);
                    localStorage.setItem('user',JSON.stringify(data.user));
                    var getUser=JSON.parse(JSON.stringify(data.user));
                    if(getUser.company){
                        $state.go('/');
                    }else{
                        $scope.pop01 = true;
                        $scope.content="请完善公司名称或个人姓名。";
                    }
                    //$state.go('/');
                }).error(function (data,status) {
                    $scope.logInfo = '登录失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
        $('#goCenter').click(function(e){
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $state.go('tab.center');
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $('#next').click(function(e){
            $scope.pop1=false;
            $state.go('/');
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        })
    })
    .controller('ResetPassCtrl',function($scope,$state,$window,$timeout,$interval,LoginService,AuthenticationService){
        $scope.msgcode1='';
        $scope.user = {btnVal:' 获取验证码 '};

        $scope.logInfo='';
        $scope.getCode = function(){
            if(!isNaN($scope.user.btnVal)){
                return;
            }
            if($scope.user.phone==null||$scope.user.phone.length<11){
                $scope.logInfo = '请输入正确手机号码';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            if($scope.user.password==null||$scope.user.password.length<6){
                $scope.logInfo = '密码不能小于6位';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            LoginService.getCode($scope.user.phone,'resetPass')
                .success(function(data,status){
                    if(data=='nouser'){
                        return $scope.logInfo = '账号不存在！';

                    }else if(data=='err'){
                        return $scope.logInfo = '验证码获取失败！';
                    }

                    $scope.msgcode1=data;
                    $scope.user.btnVal=60;
                    var timer = $interval(function(){
                        $scope.user.btnVal-=1;
                        if($scope.user.btnVal==0){
                            $scope.user.btnVal='  重新获取  ';
                            $scope.msgcode1='';
                            $interval.cancel(timer);
                        }
                    },1000);

                }).error(function (data,status) {
                    $scope.logInfo = '获取验证码失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
        $scope.reset = function(){
            if($scope.user.msgcode!=$scope.msgcode1){
                $scope.logInfo = '验证码错误！';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }
            LoginService.resetPass($scope.user.phone,$scope.user.password)
                .success(function(data,status){
                    if(data.msg==true){
                        AuthenticationService.isLogged = false;
                        /*delete $window.sessionStorage.token;
                        delete $window.sessionStorage.user;*/
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        $state.go('login');
                    }

                }).error(function (data,status) {
                    $scope.logInfo = '重置失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }

    })
    .controller('RegisterCtrl',function($scope,$state,$window,$timeout,$interval,LoginService,AuthenticationService){
        $scope.msgcode1='';
        $scope.user = {btnVal:' 获取验证码 '};
        $scope.loginMsg='';
        $scope.lmsg = false;
        $scope.logInfo='';
        $scope.pop1=false;
        $scope.getCode = function(){
            if(!isNaN($scope.user.btnVal)){
                return;
            }
            if($scope.user.phone==null||$scope.user.phone.length<11){
                $scope.logInfo = '请输入正确手机号码';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            if($scope.user.password==null||$scope.user.password.length<6){
                $scope.logInfo = '密码不能小于6位';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            LoginService.getCode($scope.user.phone,'register')
                .success(function(data,status){
                    //alert(data);
                    if(data=='hasuser'){
                        return $scope.logInfo = '账号已存在！';

                    }else if(data=='err'){
                        return $scope.logInfo = '验证码获取失败！';
                    }


                    $scope.msgcode1=data;
                    $scope.user.btnVal=60;
                    var timer = $interval(function(){
                        $scope.user.btnVal-=1;
                        if($scope.user.btnVal==0){
                            $scope.user.btnVal='  重新获取  ';
                            $scope.msgcode1='';
                            $interval.cancel(timer);
                        }
                    },1000);

                }).error(function (data,status) {
                    $scope.logInfo = '获取验证码失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
        $scope.register = function(){

            LoginService.register($scope.user.phone,$scope.user.password)
                .success(function(data,status){
                    if(data.msg==true){
                        AuthenticationService.isLogged = false;
                        /*delete $window.sessionStorage.token;
                        delete $window.sessionStorage.user;*/
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        var countdown=5;
                        var dian='.'

                        /*$state.go('/');*/
                        LoginService.login($scope.user.phone,$scope.user.password)
                            .success(function(data,status){
                                AuthenticationService.isLogged = true;//认证成功
                                localStorage.setItem('token',data.token);
                                localStorage.setItem('user',JSON.stringify(data.user));
                                $scope.pop1=true;
                                $scope.content='注册成功，请完善公司名称或个人姓名。';
                                //$scope.lmsg = true;
                                //$scope.loginMsg = '自动登录'+dian+'  '+countdown;
                                //countdown-=1;
                                //dian+='.';
                                //var time = $interval(function(){
                                //    $scope.loginMsg = '自动登录'+dian+'  '+countdown;
                                //    if(countdown == 0){
                                //        $interval.cancel(time);
                                //        $state.go('/');
                                //    }
                                //    countdown-=1;
                                //    dian+='.';
                                //
                                //},1000);

                            }).error(function (data,status) {
                                $scope.logInfo = '登录失败';
                                $timeout(function(){
                                    $scope.logInfo = '';
                                },3000);
                            });

                    }

                }).error(function (data,status) {
                    $scope.logInfo = '注册失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
        $scope.goCenter=function(){
            $timeout(function(){
                $state.go('tab.center');
            },300);
        }

    })
    .controller('TabCtrl',function($scope,$state,$window,$location,LoginService){
        //alert('sssss');
       // document.getElementById('footer')
        $scope.num1;
        $scope.num2;
        $scope.num3;
        $scope.num4;
        if($location.$$url.indexOf('myTransfer')>-1){
            $scope.num1=1;

        }else if($location.$$url.indexOf('myOrders')>-1){
            $scope.num2=1;

        }else if($location.$$url.indexOf('bid')>-1){
            $scope.num3=1;

        }else if($location.$$url.indexOf('line')>-1){
            $scope.num4=1;
        }else if($location.$$url.indexOf('center')>-1){
            $scope.num5=1;
        }

        $scope.setColor = function(index){
            setCo();
            changeCo(index);
            console.log('sss');
        }
        function setCo(){
            $scope.num1=2;
            $scope.num2=2;
            $scope.num3=2;
            $scope.num4=2;
            $scope.num5=2;
        }

        function changeCo(index){
            switch (index){
                case 1:
                    $scope.num1=1;
                    break;
                case 2:
                    $scope.num2=1;
                    break;
                case 3:
                    $scope.num3=1;
                    break;
                case 4:
                    $scope.num4=1;
                    break;
                case 5:
                    $scope.num5=1;
                    break;
            }

        }
    })
    .controller('CitysCtrl',function($scope,$state,$stateParams,TransferService){
        $scope.citys = TransferService.getCityList();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
        },500);
        $scope.goBack = function(){
            $state.go('tab.transfer');
        };
        $scope.selectCity = function(id,city){//判断上一页面传来的值是1则改变事发地点2为目的地
            if($stateParams.type==1){
                TransferService.getInforData().startCityId = id;
                TransferService.getInforData().startCity = city;

            }else if($stateParams.type==2){
                TransferService.getInforData().endCityId = id;
                TransferService.getInforData().endCity = city;
            }
            $state.go('tab.transfer');
        };
    })
    .controller('TransferAddCarCtrl',function($scope,$state,$stateParams,$window,TransferService,CropperService){
        if(!TransferService.getCarbrandList().carbrand.length>0){
            TransferService.getCarbrands($scope);//查询汽车品牌
        }

        $scope.visible = true;
        $scope.color = 1;
        $scope.color1 = 2;
        $scope.toggle = function (t) {//显示隐藏零散车辆和整板车辆
            if(t==1){
                $scope.visible = true;
                $scope.color = 1;
                $scope.color1 = 2;
                $scope.inforData.type = 1;
                TransferService.getCurrenttab().state = false;
            }else{
                $scope.visible = false;
                $scope.color1 = 1;
                $scope.color = 2;
                $scope.inforData.type = 2;//设置发车类型
                TransferService.getCurrenttab().state = true;
            }
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.myScroll.refresh();
            },500);
        }

        $scope.inforData = TransferService.getInforData();
        $scope.currentcar = TransferService.getCurrentCar();//当前显示的品牌和型号
        $scope.currentcar.cropper = CropperService.getCropperdata()[0];
        $scope.currentcar.filepath = CropperService.getCropperdata()[0].filename;
        $scope.currentcar.filename = CropperService.getCropperdata()[0].filepath;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,tap:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        if(TransferService.getCurrenttab().state){//设置那个tab显示
            $scope.visible = false;
            $scope.color1 = 1;
            $scope.color = 2;
            $scope.inforData.type = 2;//设置发车类型
        }

        setTimeout(function(){//延迟绑定点击事件
            $scope.myScroll.refresh();
            $scope.up = document.getElementById('uploadImg');
            $scope.cl = document.getElementById('uploadfile');
            $scope.carbrand = document.getElementById('carbrand');
            $scope.carnum = document.getElementById('carnum');
            $scope.plusnum = document.getElementById('plusnum');
            $scope.minusnum = document.getElementById('minusnum');
            $scope.dray11 = document.getElementById('dray11');
            $scope.dray22 = document.getElementById('dray22');
            /*$scope.goback = document.getElementById('goback');*/
            /*$scope.cl.addEventListener('tap', function () {
                alert('dddddd');
            }, false);*/
            $scope.up.addEventListener('tap', function () {
                $state.go('tab.cropper',{scale1:4,scale2:3,width:640,height:480,urltype:'transfer'});
                //$('#uploadfile').click();//点击隐藏的文件上传按钮
            }, false);
            $scope.carbrand.addEventListener('tap', function () {

                $state.go('tab.getCarBrandList');
            }, false);
            $scope.carnum.addEventListener('tap', function () {
                /*alert('nnnnnnnn');*/
                $state.go('tab.getCarNumList');
            }, false);
            $scope.plusnum.addEventListener('tap', function () {
                $scope.currentcar.carnumber+=1;
                //$scope.inforData.carnumber+=1;
                $scope.$apply();
                //TransferService.getInforData().carnumber =  $scope.inforData.carnumber;
                console.log($scope.inforData.carnumber);
            }, false);
            $scope.minusnum.addEventListener('tap', function () {
                $scope.currentcar.carnumber-=1;
                //$scope.inforData.carnumber-=1;
                $scope.$apply();
                //TransferService.getInforData().carnumber =  $scope.inforData.carnumber;
            }, false);
            /*$scope.goback.addEventListener('tap', function () {
             $state.go('tab.transfer');//返回到上一页
             }, false);*/
            $scope.dray11.addEventListener('tap', function () {
                $('#dray1').click();
            }, false);
            $scope.dray22.addEventListener('tap', function () {
                $('#dray2').click();
            }, false);
        },500);

        $scope.goBack = function(){
            $state.go('tab.transfer');
        };
        $scope.Carlist = function(){
            $state.go('tab.carlist');
        }
        $scope.goCropper = function(){
            $state.go('tab.cropper');
        }

        $scope.savetransfer = function(){
            if($scope.inforData.username==''||$scope.inforData.phone==''){
                alert('请返回填写用户姓名和手机号码')
                return;
            }
            //零散车辆类型并且carnum大于0，不存在添加当前页面数据到数组
            if($scope.inforData.type==2){//整板车类型不需要把当前页面默认选中的值添加进来
                TransferService.savetransfer()
                    .success(function(data,status){
                    if(data){

                        TransferService.resetInforData();
                        $scope.currentcar = TransferService.resetCurrentCar();
                        $state.go('tab.complete',{isOk:true});
                        //alert('发布成功');
                    }else{
                        $state.go('tab.complete',{isOk:false});
                    }
                }).error(function(data,status){
                        $state.go('tab.complete',{isOk:false});
                });
            }else if($scope.inforData.type==1){//&&$scope.inforData.carnum.length>0
                if($scope.currentcar.brand=='品牌'||$scope.currentcar.num=='型号',$scope.currentcar.carnumber<0){//||$scope.currentcar.filepath==''
                        if($scope.inforData.carnum.length<1){
                            return alert('请检查是否选择正确');
                        }
                }else{
                    $scope.inforData.carnum.push($scope.currentcar);
                }
                $scope.currentcar = TransferService.resetCurrentCar();
                TransferService.savetransfer()
                    .success(function(data,status){
                        if(data){
                            CropperService.getCropperdata()[0]={
                                scale1:'',
                                scale2:'',
                                width:'',
                                height:'',
                                filename:'',
                                filepath:'文件名'
                            };
                            TransferService.resetInforData();//重置页面数据
                            $scope.currentcar = TransferService.resetCurrentCar();
                            $state.go('tab.complete',{isOk:true});
                            //alert('发布成功');
                        }else{
                            $state.go('tab.complete',{isOk:false});
                        }


                    }).error(function(data,status){
                        $state.go('tab.complete',{isOk:false});
                    });
            }

        };

        $scope.dray=TransferService.getDray();
        //var currentcar = $scope.currentcar;
        $scope.addCar = function(type){//添加车辆

            if(type==1){
                if($scope.currentcar.brand=='品牌'||$scope.currentcar.num=='型号',$scope.currentcar.carnumber<0){//||$scope.currentcar.filepath==''

                    alert('请检查是否选择正确');
                    return false;
                }
                $scope.inforData.carnum.push($scope.currentcar);
                CropperService.getCropperdata()[0]={
                    scale1:'',
                    scale2:'',
                    width:'',
                    height:'',
                    filename:'',
                    filepath:'文件名'
                };
            }else{
                $scope.inforData.draynum.push($scope.dray.value);
                $scope.dray.num+=1;
            }

            //currentcar = null;
            $scope.currentcar = TransferService.resetCurrentCar();
            $scope.dray.value = 12;
            return true;
        };


        /*$scope.selectCarbrand = function(){
            $state.go('tab.getCarBrandList');
        }*/

        $('#uploadfile').bind('change',function(){//jquery监听隐藏文本框值变化

            var fd = new FormData();
            fd.append("name", "车辆图片");
            fd.append("files", document.getElementById("uploadfile").files[0]);

            $scope.currentcar.filename = '';
            $scope.$apply();

            var xhr = new XMLHttpRequest();
            xhr.open("POST" ,"/uploadFiles" , true);
            xhr.setRequestHeader('Authorization','Bearer ' +  localStorage.getItem('token'))//$window.sessionStorage.token
            xhr.upload.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    document.getElementById('progress').innerHTML = '已上传 '+percentComplete.toString() + '%';
                }


            }, false);
            xhr.send(fd);
            xhr.onload = function(e) {
                if (this.status == 200) {
                    //$scope.inforData.fileName = this.responseText;
                    document.getElementById('progress').innerHTML = '';
                    $scope.currentcar.filepath = this.responseText;
                    $scope.currentcar.filename = this.responseText.substring(0,10)+'.jpg';
                    $scope.$apply();
                }
            };

        });

    })
    .controller('CarBrandListCtrl',function($scope,$state,$stateParams,TransferService){

        $scope.carbrands = TransferService.getCarbrandList().carbrand;

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
        },500);

        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.selectCarbrand = function(id,brand){
            TransferService.getCurrentCar().brand = brand;
            TransferService.getCurrentCar().bid = id;
            /*TransferService.getInforData().carnum.push(id);*/
            /*TransferService.getInforData().carbrand = brand;
            TransferService.getInforData().carbrandid = id;*/
            //选定车牌后请求对应型号
            TransferService.getCurrentCar().num='型号';
            TransferService.getCarbrandList().carnums=[];
            TransferService.getCarNumList(id);

            $state.go('tab.transferAddCar');
        }

    })
    .controller('CarNumListCtrl',function($scope,$state,$stateParams,TransferService){

        $scope.carnums = TransferService.getCarbrandList().carnums;//TransferService.getCarNums();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
        },500);

        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.selectCarnum = function(id,num){
            TransferService.getCurrentCar().num = num;
            TransferService.getCurrentCar().nid = id;
            //TransferService.getInforData().carnum.push(id);
            /*TransferService.getInforData().carnumid = id;*/
            $state.go('tab.transferAddCar');
        }

    })
    .controller('CarListCtrl',function($scope,$state,$stateParams,TransferService){

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);


        $scope.inforData = TransferService.getInforData();
        $scope.type = $scope.inforData.type;
        if($scope.type==1){
            $scope.carnum = $scope.inforData.carnum;//获取车辆数组
            TransferService.getCurrenttab().state = false;//设置零散车辆为默认显示的页面
        }else{
            TransferService.getCurrenttab().state = true;

            $scope.draylsit=[];
            $scope.draynum = $scope.inforData.draynum;
            for(var i=0;i<$scope.draynum.length;i++){
                if($scope.draynum[i]==12){
                    $scope.draylsit.push({type:'小板',num:12});
                }else{
                    $scope.draylsit.push({type:'大板',num:24});
                }
            }
        }
        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.delSelect = function(index){
            if(!confirm("确定要删除此项吗？")){
                return;
            }
            if($scope.type==1){
                $scope.carnum.splice(index,1);//删除选中的元素
            }else{
                $scope.draynum.splice(index,1);
                $scope.draylsit.splice(index,1);
                TransferService.getDray().num-=1;
            }
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },300);

    })
    .controller('CompleteCtrl',function($scope,$state,$stateParams,TransferService){
        $scope.isOk = $stateParams.isOk;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);


        $scope.goBack = function(){
            $state.go('tab.transfer');
        };

    })
    .controller('CropperCtrl',function($scope,$state,$stateParams){
        $scope.scale1 = $stateParams.scale1;
        $scope.scale2 = $stateParams.scale2;
        $scope.width = $stateParams.width;
        $scope.height = $stateParams.height;
        $scope.urltype = $stateParams.urltype;
        $scope.goBack = function(){
            if($stateParams.urltype=='transfer'){//判断哪个页面进来的，回到哪个页面
                $state.go('tab.transferAddCar');
            }else if($stateParams.urltype == 'upheader'){
                $state.go('tab.center');
            }

        };



    });

